<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class UserSetting extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'user_id',
        'user_type', // tenant, admin, freelancer
        'setting_key',
        'setting_value',
        'setting_type', // security, notification, personal
        'is_encrypted'
    ];

    protected $casts = [
        'setting_value' => 'json',
        'is_encrypted' => 'boolean'
    ];

    protected $dates = ['deleted_at'];

    // 关联用户（多态关联）
    public function user()
    {
        return $this->morphTo();
    }

    // 设置类型常量
    const TYPE_SECURITY = 'security';
    const TYPE_NOTIFICATION = 'notification';
    const TYPE_PERSONAL = 'personal';

    // 获取设置类型显示名称
    public function getSettingTypeDisplayAttribute()
    {
        $types = [
            self::TYPE_SECURITY => '安全设置',
            self::TYPE_NOTIFICATION => '通知设置',
            self::TYPE_PERSONAL => '个人设置'
        ];

        return $types[$this->setting_type] ?? '未知类型';
    }

    // 获取用户的特定设置
    public static function getUserSetting($userId, $userType, $settingKey, $default = null)
    {
        $setting = self::where('user_id', $userId)
            ->where('user_type', $userType)
            ->where('setting_key', $settingKey)
            ->first();

        return $setting ? $setting->setting_value : $default;
    }

    // 设置用户配置
    public static function setUserSetting($userId, $userType, $settingKey, $settingValue, $settingType = self::TYPE_PERSONAL)
    {
        return self::updateOrCreate(
            [
                'user_id' => $userId,
                'user_type' => $userType,
                'setting_key' => $settingKey
            ],
            [
                'setting_value' => $settingValue,
                'setting_type' => $settingType
            ]
        );
    }
}